/**
 * http://www.koorz.com
 * Copyright (c) 2012 shanghai meiku information technology co,.ltd
 */
package com.koorz.interceptor.checkStyle;

import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.jfinal.aop.Interceptor;
import com.jfinal.core.ActionInvocation;
import com.koorz.modules.user.User;
import com.koorz.utils.ActionUtils;
import com.koorz.utils.SessionContext;

/**
 * 功能描述：审核搭配时用于检查数据同步，超过时间的提示已经不能提交了。
 * 作        者：尹东东 
 * 创建时间：2013-5-24 下午6:08:57
 * 版  本  号：1.0
 */
public class CheckStyleInterceptor implements Interceptor {

	@Override
	public void intercept(ActionInvocation ai) {
		String key = ai.getActionKey();
		User user = SessionContext.get().user();
		TaskService taskService = TaskService.getInstance();
		if(StringUtils.endsWith(key, "checked")){
			ITask task = taskService.getTask(user.getStr("id"));
			if(task != null && task.isTimeout()){
				taskService.stopTask(task, user.getStr("id"));
				ai.getController().renderJson(ActionUtils.result(ActionUtils.CODE_100, "审核时间超时，请刷新页面重新选择！"));
			}else {
				ai.invoke();
				taskService.stopTask(task, user.getStr("id"));
			}
		}else {
			ITask task = new CheckTask(user.getStr("id"));
			if(TaskService.getInstance().addTask(user.getStr("id"), task)){
				List<String> result = taskService.getAllData();
				if(result.size() > 0){
					ai.getController().getRequest().setAttribute("filter", StringUtils.join(result,","));
				}else {
					ai.getController().getRequest().setAttribute("filter", "");
				}
				ai.invoke();
				task.start();
			}else {
				taskService.stopTask(task, user.getStr("id"));
				ai.getController().renderJson(ActionUtils.result(ActionUtils.CODE_100, "您有未审核完的任务，请审核完或刷新页面重新选择！"));
			}
		}
	}
}
